package com.yanqu.road.server.cmd.activity.douluodalu;

import com.yanqu.road.logic.config.GameConfig;
import com.yanqu.road.pb.activity.douluodalu.DouLuoDaLuProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.douluodalu.DouLuoDaLuModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.gameplayer.module.player.PreReduceModule;
import com.yanqu.road.server.manger.activity.douluodalu.DouLuoDaLuMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;

@Cmd(code = Protocol.S_DOU_LUO_DA_LU_TEAM_CREATE,desc = "创建队伍")
public class DouLuoDaLuCreateTeamCmd extends AbstractCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        if ((ret = DouLuoDaLuMgr.canEntryActivity(player)) != 0) return;

        //v4.3 活动期间可操作
        //ret = DouLuoDaLuMgr.activityInCreateTeamPeriod();
        //if(ret != 0){
        //    return;
        //}
        DouLuoDaLuProto.DouLuoDaLuCreateTeamReqMsg reqMsg = DouLuoDaLuProto.DouLuoDaLuCreateTeamReqMsg.parseFrom(packet.getBytes());
        String teamName = StringUtils.clearHeadAndTailEmpty(reqMsg.getTeamName());
        ret = DouLuoDaLuMgr.checkTeamName(teamName);
        if(ret != 0){
            return;
        }
        DouLuoDaLuProto.DouLuoDaLuCreateTeamCrossReqMsg.Builder crossReqMsg = DouLuoDaLuProto.DouLuoDaLuCreateTeamCrossReqMsg.newBuilder();
        Property property = new Property(GameConfig.GAME_MONEY_INGOTS, BigInteger.valueOf(DouLuoDaLuMgr.getConfig().TEAM_CREATE_NEED_INGOTS));
        if(player.getModule(CurrencyModule.class).currencyIsEnough(property)){
            crossReqMsg.setHasEnoughItems(true);
            // 预扣除
            player.getModule(PreReduceModule.class).preReduce(property);
            player.getModule(DouLuoDaLuModule.class).createTeamProperty = property;
        }
        crossReqMsg.setActivityId(DouLuoDaLuMgr.getActivityInfo().getActivityId());
        crossReqMsg.setTeamName(reqMsg.getTeamName());

        player.sendUnionActivityGroupPacket(Protocol.C_DOU_LUO_DA_LU_TEAM_CREATE, crossReqMsg, crossReqMsg.getActivityId());

    }

    @Override
    public void sendData(GamePlayer player) {
        if(ret != 0){
            DouLuoDaLuProto.DouLuoDaLuCreateTeamRespMsg.Builder respMsg = DouLuoDaLuProto.DouLuoDaLuCreateTeamRespMsg.newBuilder();
            respMsg.setRet(ret);
            player.sendPacket(Protocol.U_DOU_LUO_DA_LU_TEAM_CREATE, respMsg);
        }
    }
}
